package com.banshuibao.bsb_android.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.ChangePhoneModel;
import com.banshuibao.bsb_android.model.SendSmsModel;
import com.banshuibao.bsb_android.util.GetLoginInfo;
import com.banshuibao.bsb_android.util.ImageUtil;
import com.banshuibao.bsb_android.util.IntentManager;
import com.banshuibao.bsb_android.util.XToast;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ChangePhoneActivity extends BaseActivity implements View.OnClickListener {

    private EditText edit_phone, edit_number_one, edit_number_two;
    private ImageView btn_iv;
    private TextView btn_tv, commit;

    //请求验证码的唯一标识
    private String string;
    private int isSelected = 1;
    //获取的短信唯一标识
    private String smsMessageSid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_phone);
        initView();
    }

    //获取验证码倒计时
    CountDownTimer timer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            btn_tv.setText(millisUntilFinished / 1000 + "秒");
            btn_tv.setTextColor(getResources().getColor(R.color.get_message));
        }

        @Override
        public void onFinish() {
            btn_tv.setEnabled(true);
            btn_tv.setText("重新获取");
        }
    };

    private void initView() {
        setTitleText("修改手机号");
        edit_phone = findViewById(R.id.change_phone_edit);
        edit_number_one = findViewById(R.id.change_number_edit);
        edit_number_two = findViewById(R.id.change_number_two_edit);
        btn_iv = findViewById(R.id.iv_btn);
        btn_tv = findViewById(R.id.tv_btn);
        commit = findViewById(R.id.preservation_btn);
        btn_iv.setOnClickListener(this);
        btn_tv.setOnClickListener(this);
        commit.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getDataPost();
    }

    private void getDataPost() {
        string = getTime();
        ImageUtil.loadNumberImage(this, Constants.Url.GET_CODE + string, btn_iv);
    }

    private String getTime() {
        long time = System.currentTimeMillis() / 1000;//获取系统时间的10位的时间戳
        Random random = new Random();
        String sRand = "";
        for (int i = 0; i < 4; i++) {
            String rand = String.valueOf(random.nextInt(10));
            sRand += rand;
        }
        return "code_" + sRand + String.valueOf(time);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_btn:
                getDataPost();
                break;
            case R.id.tv_btn:
                isSelected = 2;
                String phone = edit_phone.getText().toString().trim();
                String number = edit_number_one.getText().toString().trim();
                if (isMatchMobilLength(phone, 11) && isMobilNo(phone)) {
                    if (!TextUtils.isEmpty(number) && number.length() == 4) {
                        getMessageNumber(phone, number);
                    } else {
                        XToast.showToast(this, "请输入右侧数字");
                    }
                } else {
                    XToast.showToast(this, "请输入正确电话号码");
                }
                break;
            case R.id.preservation_btn:
                String userId = GetLoginInfo.getLoginInfoInstance(this).readUser().getUserId();
                String phone1 = edit_phone.getText().toString().trim();
                String number1 = edit_number_one.getText().toString().trim();
                String number2 = edit_number_two.getText().toString().trim();
                if (!TextUtils.isEmpty(phone1) && isMobilNo(phone1) && isMatchMobilLength(phone1, 11)) {
                    if (!TextUtils.isEmpty(number1) && number1.length() == 4) {
                        if (isSelected == 2) {
                            if (!TextUtils.isEmpty(number2)) {
                                try {
                                    showProgressDialog();
                                    setPost( phone1, userId, number2);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                XToast.showToast(this, "请输入验证码");
                            }
                        } else {
                            XToast.showToast(this, "请获取验证码");
                        }
                    } else {
                        XToast.showToast(this, "请正确输入右侧数字");
                    }
                } else {
                    XToast.showToast(this, "请输入正确手机号");
                }
                break;
        }
    }

    private void setPost(String phone1, String userId, String number2) {
        ChangePhoneModel model = new ChangePhoneModel();
        model.setPhone(phone1);
        model.setSmsCode(number2);
        model.setUuid(userId);
        model.setSmsMessageSid(smsMessageSid);
        HttpUtil.doPost(Constants.Url.CHANGE_PHONE, model, new HttpResponse(this) {
            @Override
            public void onResult(Object obj) {
//                String s = (String) obj;
//                LogUtil.e(s);
                XToast.showToast(ChangePhoneActivity.this,"修改成功,请使用新手机号码重新登录");
                cancelProgressDialog();
                IntentManager.goLoginActivity(ChangePhoneActivity.this);
                finish();
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                cancelProgressDialog();
            }
        });
    }

    private void getMessageNumber(String phone, String number) {
        SendSmsModel.body body = new SendSmsModel.body();
        body.setPhone(phone);
        body.setImgCode(number);
        body.setSendtype("UR");
        body.setCodeMessage(string);
        HttpUtil.doPost(Constants.Url.SEND_SMS, body, new HttpResponse(this, SendSmsModel.class) {
            @Override
            public void onResult(Object obj) {
                timer.start();
                SendSmsModel sendSmsModel = (SendSmsModel) obj;
                smsMessageSid = sendSmsModel.getSmsMessageSid();
            }
        });
    }

    public boolean isMatchMobilLength(String phone, int length) {
        if (!TextUtils.isEmpty(phone)) {
            return phone.length() == length;
        }
        return false;
    }

    public boolean isMobilNo(String phone) {
        String repexp = "^[1][345789]\\d{9}";
        Pattern pattern = Pattern.compile(repexp);
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }

    //点击隐藏输入框之外 隐藏输入框
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    //取消
    @Override
    protected void onDestroy() {
        timer.cancel();
        super.onDestroy();
    }
}
